/*
 * aksDraw.c
 *
 *  Created on: 2011/06/18
 *      Author: AKS
 */

#include "app/cv/include/aksImage.h"
#include "app/cv/include/aksDraw.h"
#include "app/cv/include/font.h"

void aksLine(AksImage *img, AksPoint p1, AksPoint p2, AksPixel color)
{
	if(p1.x > p2.x || p1.y > p2.y)
	{
		AksPoint tmp = p1;
		p1 = p2;
		p2 = tmp;
	}

	SWORD dx = (SWORD)p2.x - (SWORD)p1.x;
	SWORD dy = (SWORD)p2.y - (SWORD)p1.y;

	SWORD w = 0;
	SWORD h = 0;

	SWORD error = 0;

	if(dx > dy)
	{
		for(w=0 ; w<dx ; w++)
		{
			error += dy;
			if(error > dx)
			{
				error -= dx;
				h++;
			}

			aksSet2D(img, p1.x+w, p1.y+h, color);
		}
	}
	else
	{
		for(h=0 ; h<dy ; h++)
		{
			error += dx;

			if(error > dy)
			{
				error -= dy;
				w++;
			}

			aksSet2D(img, p1.x+w, p1.y+h, color);
		}
	}

	return;
}

void aksDrawRect(AksImage *img, AksPoint p1, AksPoint p2, AksPixel color)
{
	if(p1.x > p2.x)
	{
		WORD tmp = p1.x;
		p1.x = p2.x;
		p2.x = tmp;
	}

	if(p1.y > p2.y)
	{
		WORD tmp = p1.y;
		p1.y = p2.y;
		p2.y = tmp;
	}

	aksLine(img, aksPoint(p1.x, p1.y), aksPoint(p2.x, p1.y), color);
	aksLine(img, aksPoint(p2.x, p1.y), aksPoint(p2.x, p2.y), color);
	aksLine(img, aksPoint(p2.x, p2.y), aksPoint(p1.x, p2.y), color);
	aksLine(img, aksPoint(p1.x, p2.y), aksPoint(p1.x, p1.y), color);

	return;
}

void akdDrawFilledRect(AksImage *img, AksPoint p1, AksPoint p2, AksPixel color)
{
	if(p1.x > p2.x)
	{
		WORD tmp = p1.x;
		p1.x = p2.x;
		p2.x = tmp;
	}

	if(p1.y > p2.y)
	{
		WORD tmp = p1.y;
		p1.y = p2.y;
		p2.y = tmp;
	}

	for(WORD i = p1.y ; i < p2.y ; ++i)
	{
		for(WORD j = p1.x ; j < p2.x ; ++j)
		{
			aksSet2D(img, j, i, color);
		}
	}
}

/* ------  ------ */
void aksDrawCharactor(AksImage *img, AksPoint pos, AksPixel color, BYTE ch)
{
    // draw charactor 6x8
    for(BYTE y=0 ; y<9 ; y++)
	{
	    BYTE x=0;
        for(BYTE msk = 0x20 ; msk > 0 ; msk = msk>>1, x++)
		{
            if(fontset[ch][y] & msk)
			{
                aksSet2D(img, pos.x + x, pos.y + y, color);
			}
		}
	}

    return;
}


void aksDrawStrings(AksImage *img, AksPoint pos, AksPixel color, BYTE *str)
{
    AksPoint p;
	p.x = pos.x;
	p.y = pos.y;

	while(*str)
	{
        aksDrawCharactor(img, p, color, *str);

        p.x += 6;
        str++;
	}

    return;
}

